package cn.edu.nju.software.androidsymplayer.musicservice;

import java.util.List;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;

public class SensorService extends Service implements SensorEventListener {
	private CommandReceiver doCommand;
	private SensorManager sm;
	static final String SENSOR_CONTROL = "SymPlayer.SENSOR_CONTROL";
	public static final String UPDATE_STATUS = "SymPlayer.ACTION_UPDATE";

	public static final int SENSOR_UPDATE = 101;
	public static final int SENSOR_FORWARD = 102;
	public static final int SENSOR_BACKWARD = 103;
	private int count = 0;

	int status = 1;

	@Override
	public void onCreate() {
		doCommand = new CommandReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(SENSOR_CONTROL);
		registerReceiver(doCommand, filter);
		sm = (SensorManager) getSystemService(SENSOR_SERVICE);
		List<Sensor> list2 = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
		for (int i = 0; i < list2.size(); i++)
			sm.registerListener(this, list2.get(i),
					SensorManager.SENSOR_DELAY_UI);
		Log.d("123", "debug03");
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		if (count != 0)
			count--;
		Sensor sensor = event.sensor;
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		float offset = (float) 9.8
				- ((float) Math.sqrt(Math.pow(y, 2) + Math.pow(z, 2)));
		if (x > 0)
			x -= offset;
		else if (x < 0)
			x += offset;
		synchronized (this) {
			if (sensor.getType() == Sensor.TYPE_ACCELEROMETER && count == 0) {
				if (x > 8) {
					status = SENSOR_BACKWARD;
					updateUi();
					count = 10;
				} else if (x < -8) {
					status = SENSOR_FORWARD;
					updateUi();
					count = 10;
				}
			}
		}
	}

	public class CommandReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			switch (intent.getIntExtra("cmd", -1)) {
			}
		}
	}

	@Override
	public void onDestroy() {
		sm.unregisterListener(this);
		unregisterReceiver(doCommand);
	}

	private void updateUi() {
		Intent intent = new Intent(UPDATE_STATUS);
		intent.putExtra("status", status);
		sendBroadcast(intent);
	}
}
